package com.ihmp.dao;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ihmp.model.TProductInRoom;
import com.ihmp.model.TProductInRoomPriceHistory;

@Repository("productInRoomDAO")
public class CProductInRoomDAO implements IProductInRoomDAO{
	
	@Autowired
	private SessionFactory sessionFactory;

	public void saveOrUpdate(TProductInRoom product) {		
		sessionFactory.getCurrentSession().saveOrUpdate(product);
	}
	
	public void delete(TProductInRoom product) {		
		sessionFactory.getCurrentSession().delete(product);
	}

	public TProductInRoom get(Integer id) {		
		return (TProductInRoom) sessionFactory.getCurrentSession().get(TProductInRoom.class, id);
		
	}

	@SuppressWarnings("unchecked")
	public List<TProductInRoom> list() {					
		Criteria crit = sessionFactory.getCurrentSession().createCriteria(TProductInRoom.class);
		crit.addOrder(Order.desc("createDate"));
		crit.addOrder(Order.desc("editDate"));
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public List<TProductInRoom> list(int page,int recordPerPage) {		
		Criteria crit = sessionFactory.getCurrentSession().createCriteria(TProductInRoom.class);
		crit.setFirstResult((page-1)*recordPerPage).setMaxResults(page*recordPerPage -1);
		crit.addOrder(Order.desc("createDate"));
		crit.addOrder(Order.desc("editDate"));
		return crit.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<String> grid(){
		ArrayList<String> grid = new ArrayList<String>();
		Query query = sessionFactory.getCurrentSession().createSQLQuery("CALL Store_ProductInRoomGrid")
					  .addEntity(TProductInRoom.class).addEntity(TProductInRoomPriceHistory.class);				
		grid = (ArrayList<String>) query.list();
		return grid;
	}
	
	@SuppressWarnings("unchecked")
	public List<String> grid(int page,int recordPerPage){
		ArrayList<String> grid = new ArrayList<String>();
		Query query = sessionFactory.getCurrentSession().createSQLQuery("CALL Store_ProductInRoomGrid");
		grid = (ArrayList<String>) query.list();
		return grid;
	}
	
	public LinkedHashMap<Integer, String> getComboData(){
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
		ArrayList<TProductInRoom> productList = (ArrayList<TProductInRoom>) list();
		for(TProductInRoom product : productList){
			map.put(product.getId(), product.getName());
		}
		return map;
	}
	
}
